package com.chart.web.controller.chart.sta;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.chart.chart.domian.ChartConfigs;
import com.chart.chart.domian.dto.ChartDateTto;
import com.chart.chart.domian.utils.ChartValidator;
import com.chart.chart.domian.vo.ChartSmartVo;
import com.chart.chart.service.IChartConfigsService;
import com.chart.common.core.controller.BaseController;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.utils.ChartDataUtils;
import com.chart.common.utils.ColorUtils;
import com.chart.common.utils.ExcelDataUtils;
import com.chart.common.utils.ExcelUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * K线
 *
 * @author chart
 */
@RestController
@RequestMapping("/kline/chart")
public class BasicKlineChartController extends BaseController {


    @Autowired
    private IChartConfigsService chartConfigsService;


    //基础K线图
    @PostMapping("/basic/importData")
    public AjaxResult importData(@RequestBody ChartDateTto chartDateTto) throws Exception {
        // 参数校验
        String validationMessage = ChartValidator.check(chartDateTto);
        if (validationMessage != null) {
        // 返回校验失败的提示信息给前端
            return AjaxResult.error(validationMessage);
        }
        List<List<String>> lists = extractDataFromList(chartDateTto.getDataList());
        lists.remove(0);  // 移除第一行

        for (List<String> list : lists) {
            System.out.println("dqadodqaaaa哈哈哈" + list);
        }
        // 用于存放每一行（去掉第一列）的数据
        ArrayList<ArrayList<String>> arrayList = new ArrayList<>();  // 类型改为 ArrayList<ArrayList<String>>
        for (ArrayList<String> o : arrayList) {
            System.out.println("我是每行的数据" + o);
        }

        // 获取seriesName列表
        ArrayList<String> seriesName = new ArrayList<>(); // 第一类的数据
        // 遍历excel的每一行数据
        for (int rowIndex = 0; rowIndex < lists.size(); rowIndex++) {
            List<String> row = lists.get(rowIndex);
            System.out.println("正在处理第 " + (rowIndex + 1) + " 行:");
            // 第一列的数据放入 seriesName 集合中
            String s = row.get(0);  // 获取每一行的第一列
            seriesName.add(s);

            // 创建一个临时列表，用于存放当前行去掉第一列的数据
            ArrayList<String> rowWithoutFirstCol = new ArrayList<>();

            // 遍历当前行中的每一列，从第二列开始（即 colIndex = 1）
            for (int colIndex = 1; colIndex < row.size(); colIndex++) {
                String cellValue = row.get(colIndex);
                System.out.println("  第 " + (colIndex + 1) + " 列: " + cellValue);
                // 将非第一列的数据放入 rowWithoutFirstCol 列表
                rowWithoutFirstCol.add(cellValue);
            }

            // 将处理好的当前行（去掉第一列）数据添加到 arrayList 中
            arrayList.add(rowWithoutFirstCol);
        }

        // 输出 seriesName 列表中的内容（第一列数据）
        for (String sssss : seriesName) {
            System.out.println("我是第一列第一行的数据: " + sssss);
        }

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode chartValueJson = objectMapper.readTree(chartDateTto.getChartValue());

        // 获取legend节点并更新data
        JsonNode legend = chartValueJson.path("legend");
        ChartDataUtils.updateLegendData(legend, lists);

        // 获取xAxis数组的第一个对象，并修改其data数组
        JsonNode xAxis = chartValueJson.path("xAxis");
        if (xAxis.isArray() && xAxis.size() > 0) {
            JsonNode firstXAxis = xAxis.get(0);
            JsonNode dataNode = firstXAxis.path("data");
            if (dataNode.isArray()) {
                ObjectNode firstXAxisObject = (ObjectNode) firstXAxis;
                ArrayNode newDataArray = objectMapper.createArrayNode();
                // 将 seriesName 添加到 newDataArray
                for (String name : seriesName) {
                    newDataArray.add(name);
                }
                firstXAxisObject.set("data", newDataArray);
            }
        }
          // 获取series数组的第一个对象
        JsonNode series = chartValueJson.path("series");
        if (series.isArray() && series.size() > 0) {
            JsonNode firstSeries = series.get(0);
            JsonNode seriesDataNode = firstSeries.path("data");
            if (seriesDataNode.isArray()) {
                // 清空 seriesDataNode 中的数据
                ((ArrayNode) seriesDataNode).removeAll();
                // 将 arrayList 中的数据逐行添加到 seriesDataNode
                for (ArrayList<String> rowWithoutFirstCol : arrayList) {
                    ArrayNode rowArray = objectMapper.createArrayNode();
                    for (String value : rowWithoutFirstCol) {
                        rowArray.add(value);
                    }
                    ((ArrayNode) seriesDataNode).add(rowArray);
                }
            }
        }
        String updatedChartValue = chartValueJson.toString();
        ArrayList<ChartSmartVo> newList = new ArrayList<>();
        // 获取ChartConfigs对象
        ChartConfigs configs = chartConfigsService.getById(chartDateTto.getConfigId());
        // 创建新的ChartSmartVo对象并设置属性
        ChartSmartVo chartSmartVo = new ChartSmartVo();
        chartSmartVo.setConfigId(configs.getId()); // 假设ChartConfigs有getId方法
        chartSmartVo.setConfigName(configs.getConfigName()); // 假设ChartConfigs有getName方法
        chartSmartVo.setConfigValue(updatedChartValue);
        chartSmartVo.setChartTypeId(configs.getChartTypeId());
        newList.add(chartSmartVo);
        System.out.println(updatedChartValue);
        return AjaxResult.success(newList);
    }








/*   之前的 @PostMapping("/basic/importData")
    public AjaxResult importData(MultipartFile file,Long configId) throws Exception {
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);
            //获取
            List<List<String>> getdata = ExcelDataUtils.getData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            List<String> xlist = new ArrayList<>();
            List<List<String>> datas = new ArrayList<>();

            for (int i = 1; i < getdata.size(); i++) {
                List<String> list = getdata.get(i);
                if (!CollectionUtils.isEmpty(list)) {
                    List<String> newList = new ArrayList<>();
                    for (int i1 = 0; i1 < list.size(); i1++) {
                        String s = list.get(i1);
                        if (!ObjectUtils.isEmpty(s) && !s.equals("")) {
                            newList.add(s);
                        }
                    }

                    xlist.add(newList.get(0));
                    newList.remove(0);
                    datas.add(newList);
                }
            }

            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());

            JSONObject xAxis = (JSONObject) jsonObject.get("xAxis");
            xAxis.put("data",xlist);


            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
            for (int i = 0; i < series.size(); i++) {
                JSONObject jsonObject1 = series.get(i);
                jsonObject1.put("data",datas);
            }
            jsonObject.put("xAxis",xAxis);
            jsonObject.put("series",series);

            return AjaxResult.success(JSON.toJSONString(jsonObject));
        }finally {
            workbook.close();
        }
    }*/


    //基础K线图
    @PostMapping("/basic/v2/importData")
    public AjaxResult v2importData(@RequestBody List<Map<String, Object>> dataLists, Long configId) throws Exception {
        //   XSSFWorkbook workbook = null;
        try {
        /*    workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);*/

            Sheet sheet = ExcelUtils.convertDataListToSheetRemoveNineAndOne(dataLists);
            //获取
            List<List<String>> getdata = ExcelDataUtils.getData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            List<String> xlist = new ArrayList<>();
            List<List<String>> datas = new ArrayList<>();

            for (int i = 1; i < getdata.size(); i++) {
                List<String> list = getdata.get(i);
                if (!CollectionUtils.isEmpty(list)) {
                    List<String> newList = new ArrayList<>();
                    for (int i1 = 0; i1 < list.size(); i1++) {
                        String s = list.get(i1);
                        if (!ObjectUtils.isEmpty(s) && !s.equals("")) {
                            newList.add(s);
                        }
                    }

                    xlist.add(newList.get(0));
                    newList.remove(0);
                    datas.add(newList);
                }
            }

            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());

            JSONObject xAxis = (JSONObject) jsonObject.get("xAxis");
            xAxis.put("data", xlist);


            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
            for (int i = 0; i < series.size(); i++) {
                JSONObject jsonObject1 = series.get(i);
                jsonObject1.put("data", datas);
            }
            jsonObject.put("xAxis", xAxis);
            jsonObject.put("series", series);

            return AjaxResult.success(JSON.toJSONString(jsonObject));
        } finally {
//            workbook.close();
        }
    }

    private List<List<String>> extractDataFromList(List<Map<String, Object>> dataList) {
        List<List<String>> extractedData = new ArrayList<>();

        for (Map<String, Object> row : dataList) {

            List<String> rowData = new ArrayList<>();
            for (Map.Entry<String, Object> entry : row.entrySet()) {
                rowData.add(entry.getValue().toString());
            }

            extractedData.add(rowData);
        }
        return extractedData;
    }

}
